package com.liusaidh.utils;

import cn.hutool.core.util.CreditCodeUtil;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlShowCreateTriggerStatement;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.sun.imageio.plugins.jpeg.JPEG;
import org.apache.commons.imaging.ImageFormat;
import org.apache.commons.imaging.ImageFormats;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.Imaging;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;
import sun.net.www.content.image.gif;
import sun.net.www.content.image.jpeg;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * @author liusaidh
 * @date 2024/5/5 10:08
 * @description 用于文件上传
 */
public class FileUtil {


    public static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    public static String accessKryId = "LTAI5tEeg5V8S2Taqju63kct";
    public static String accessKeySecret = "r1ZIAd0T3oBZaeKHxqdK1x50o9yNNv";

    /**
     * 生成图片的名字
     *
     * @return 返回图片的名字
     */
    public static String randName() {
        String uuid = UUID.randomUUID().toString().substring(1, 8);
        Date date = new Date();
        long time = date.getTime();
        return uuid + time;
    }

    /**
     * 上传多张图片
     *
     * @param myFiles 上传的图片
     * @return 返回路径数组
     * @throws IOException
     */
    public static String[] upload(MultipartFile[] myFiles) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKryId, accessKeySecret);
        String bucketName = "blog-picturesss";
        List<String> list = new ArrayList<>();
        if (myFiles == null) {
            return null;
        }
        for (MultipartFile myFile : myFiles) {
            String newFileName;
            try (InputStream inputStream = myFile.getInputStream()) {
                String oldFileName = myFile.getOriginalFilename().toLowerCase();
                newFileName = FileUtil.randName() + oldFileName.substring(oldFileName.lastIndexOf("."));
                ossClient.putObject(bucketName, newFileName, inputStream);
            }
            list.add("https://blog-picturesss.oss-cn-beijing.aliyuncs.com/" + newFileName);
        }
        String[] arr = new String[list.size()];
        return list.toArray(arr);
    }

    /**
     * 上传一张图片
     *
     * @param myFile 图片
     * @return 返回图片的地址
     * @throws IOException
     */
    public static String uploadOne(MultipartFile myFile) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKryId, accessKeySecret);
        String bucketName = "user-picature";
        InputStream inputStream = myFile.getInputStream();
        String oldFileName = myFile.getOriginalFilename().toLowerCase();
        String suffixName = oldFileName.substring(oldFileName.lastIndexOf("."));
        String newFileName = FileUtil.randName() + suffixName;
        ossClient.putObject(bucketName, newFileName, inputStream);
        ossClient.shutdown();
        return "https://user-picature.oss-cn-beijing.aliyuncs.com/" + newFileName;
    }


    public static Boolean judge(@RequestParam("file") MultipartFile multipartFile) throws IllegalStateException, IOException {
        // 原始文件名称
        String fileName = multipartFile.getOriginalFilename();
        // 解析到文件后缀
        int index = fileName.lastIndexOf(".");
        String suffix = null;
        if (index == -1 || (suffix = fileName.substring(index + 1)).isEmpty()) {
            return false;
        }
        // 允许上传的文件后缀列表
        Set allowSuffix = new HashSet<>(Arrays.asList("jpg", "jpeg", "png", "gif", "tif", "tiff", "bmp"));
        if (!allowSuffix.contains(suffix.toLowerCase())) {
            return false;
        }
        // 临时文件
        File tempFile = new File(System.getProperty("java.io.tmpdir"), fileName);
            // 先把文件序列化到临时目录
            multipartFile.transferTo(tempFile);
            try {
                // 尝试IO文件，判断文件的合法性
                BufferedImage bufferedImage = ImageIO.read(tempFile);
                bufferedImage.getWidth();
                bufferedImage.getHeight();
            } catch (Exception e) {
                // IO异常，不是合法的图片文件，返回异常信息
                return false;
            }
            return true;
    }

    /**
     * 读取图片的宽和高来判断是不是图片
     * @param file 文件
     * @return  返回boolean
     */
    public static boolean isImage(MultipartFile file) {
//        if (file == null){
//            return false;
//        }
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null || image.getWidth() == 0 || image.getHeight() == 0) {
                return false;
            }
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}